import CrudService from '../global/CrudService'

let instance = null

// 后端路径
const prefix = '/rptTask'

const transformItem = (model) => {
  const { itemList = [] } = model
  const body = {
    ...model,
    item_code: itemList.map(e => e.item_code).join(';'),
    upload_type: itemList.map(e => e.item_upload_type).join(';'),
  }
  delete body.itemList
  return body
}

class Service extends CrudService {
  constructor() {
    super(prefix)
    this.deletePath = `${prefix}/deleteTask_sz`
    return instance || this
  }

  static getInstance() {
    if (!instance) {
      instance = new Service()
    }
    return instance
  }

  getList = async (model) => {
    const payload = await this.get(`${prefix}/queryTaskList_sz`, model) || {}
    const { list = [] } = payload
    list.forEach(e => {
      const { item_upload_type = '', item_code: ids = '' } = e
      if (ids) {
        const types = item_upload_type.split(',')
        e.itemList = ids.split(',').map((e, i) => ({ item_code: +e, item_upload_type: types[i] }))
      } else {
        e.itemList = []
      }
    })
    return payload
  }
  /**
   * 新增
   * @param model
   * @returns {Promise<*>}
   */
  addItem = async (model = {}) => {
    return this.post(`${prefix}/insertTask_sz`, transformItem(model))
  }

  /**
   * 编辑
   * @param model object
   * @returns {Promise<*>}
   */
  editItem = async (model) => {
    return this.post(`${prefix}/updateTask_sz`, transformItem(model))
  }
}

export default Service.getInstance()
